<template>
  <page-wrap back hide-tab title="职业测评" class="page" bgColor="transparent">
    <view class="allContainer">
      <image class="image" :src="imageSrc" mode="widthFix"></image>
      <view class="bottom-btn">
        <view
          v-if="!isShowTestMore && fromWhere != 'miniprogramZty'"
          class="left-btn"
          @click="openPersonalityBox"
          >已知性格</view
        >
        <!-- 针对中学生的版本，可以再次进行测评 -->
        <view v-if="fromWhere == 'junior'" class="right-btn">
          <view v-if="isShowTestMore" class="junior-bottom">
            <view class="junior-test-more" @click="goToAccessResult"
              >测评结果
            </view>
            <view class="junior-view-result" @click="testMore">再测一次</view>
          </view>
          <view
            v-if="isShowStartTest"
            class="startAssessment"
            @click="goToAccessResult"
          >
            开始测评
          </view>
        </view>
        <!-- 其他版本只有一次测评的机会 -->
        <view v-else class="right-btn">
          <view v-if="personId">
            <view class="startAssessment" @click="handleStartAssessment">
              开始测评
            </view>
          </view>
          <view v-else-if="isAuthSetting">
            <u-button
              :hair-line="false"
              :custom-style="customStyle"
              hover-class="none"
              class="lm-wechat"
              @click="showLoginDialog"
            >
              开始测评
            </u-button>
          </view>
          <view v-else>
            <u-button
              :hair-line="false"
              :custom-style="customStyle"
              hover-class="none"
              class="lm-wechat"
              open-type="getUserInfo"
              @getuserinfo="getUserName"
              :loading="getUserInfoLoading"
            >
              开始测评
            </u-button>
          </view>
        </view>
      </view>
      <LoginDialog
        ref="loginDialog"
        @loginSuccessBack="loginSuccessBack"
      ></LoginDialog>
      <u-popup
        v-model="showPersonalityBox"
        mode="bottom"
        border-radius="28"
        height="75%"
        :closeable="true"
      >
        <view class="title">请选择你的人格</view>
        <view class="personality-box">
          <view
            class="personality-item"
            @click="addAssessmentResultFn(item)"
            v-for="(item, index) in personalityList"
            :key="index"
            >{{ item.key }}</view
          >
        </view>
      </u-popup>
    </view>
  </page-wrap>
</template>

<script>
import WxLoginMixin from "@/mixins/wxLogin";
import { checkStatus, start } from "@/api/modules/activity";
import ShareMixin from "@/mixins/share";
import LoginDialog from "@/components/LoginDialog";
import {
  getUserInfo,
  cardRegist,
  getPersonOrDefaultCardType,
  addAssessmentResult,
} from "@/api/modules/career";

export default {
  components: {
    LoginDialog,
  },
  mixins: [WxLoginMixin, ShareMixin],
  data() {
    return {
      personalityList: [
        {
          value: "ESFP",
          key: "ESFP（表演者）",
        },
        {
          value: "ESTJ",
          key: "ESTJ（总经理）",
        },
        {
          value: "ESFJ",
          key: "ESFJ（执政官）",
        },
        {
          value: "ESTP",
          key: "ESTP（企业家）",
        },
        {
          value: "ISTJ",
          key: "ISTJ（物流师）",
        },
        {
          value: "ISFJ",
          key: "ISFJ（守卫者）",
        },
        {
          value: "ISTP",
          key: "ISTP（鉴赏家）",
        },
        {
          value: "ISFP",
          key: "ISFP（探险家）",
        },
        {
          value: "INTP",
          key: "INTP（逻辑学家）",
        },
        {
          value: "ENTP",
          key: "ENTP（辩论家）",
        },
        {
          value: "ENFP",
          key: "ENFP（竞选者）",
        },
        {
          value: "ENFJ",
          key: "ENFJ（主人公）",
        },
        {
          value: "INFP",
          key: "INFP（调停者）",
        },
        {
          value: "INTJ",
          key: "INTJ（建造师）",
        },
        {
          value: "INFJ",
          key: "INFJ（提倡者）",
        },
        {
          value: "ENTJ",
          key: "ENTJ（指挥官）",
        },
      ],
      showPersonalityBox: false,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      navHeight: 0,
      customStyle: {
        height: "94rpx",
        background: "#28cc75",
        color: "#ffffff",
        borderRadius: "8px",
        border: "none",
        letterSpacing: "10rpx",
        fontSize: "38rpx",
        fontWeight: "500",
      },
      isPay: 0, //是否完成支付，0未支付，1已支付
      resultId: 0, //答题结果id，默认0
      isFinish: 0, //是否完成答题，0未完成，1已完成
      hasRecord: 0, //是否存在答题记录，0不存在，1已存在
      sharePath: "/pagesSub/career/activity/vocationalAssessment", // 分享自定义路径
      shareTitle: "职业测评",
      fromWhere: "",
      fromSxh: "",
      toBook: "",
      imageUrl:
        "https://img3.job1001.com/ypMp/elan/images/career/vocationalAssessmentQuestion/share_cover.jpg",
      imageSrc:
        "https://img3.job1001.com/ypMp/elan/images/career/vocationalAssessmentQuestion/long_cover.jpg",
      assessmentType: "",
      isShowStartTest: false,
      isShowTestMore: false,
      cardType: "",
      assessmentVersion: uni.getStorageSync("assessmentVersion"), // v1 是老版本测评，v2 是新版本测评
    };
  },
  created() {
    this.navHeight = getApp().globalData.navHeight;
  },
  onLoad(opt) {
    console.log("opt", opt);
    this.fromWhere = opt.fromWhere || "";
    this.fromSxh = opt.fromSxh || "";
    this.toBook = opt.toBook || "";
    // 此处分两种情况：1. 顾问点击头像后，进到用户职途专区，可以点击进来这个页面
    // 2.用户自己从职途首页和职途专区点击进来
    if (this.fromWhere == "careerPath") {
      this.personId = opt.personId || "";
    } else if (this.fromSxh == "sxh") {
      // 如果是从双选会进来，就使用假的personId做题
      this.personId = uni.getStorageSync("SxhPersonId");
    } else if (this.fromWhere !== "junior") {
      this.checkAuthSetting();
    }
    if (this.fromWhere == "junior") {
      this.assessmentType = "1";
      this.getCheckStatus();
      this.imageSrc =
        "https://img3.job1001.com/ypMp/elan/images/career/vocationalAssessmentQuestion/long_cover_nopay.jpg?v=1";
    } else {
      this.assessmentType = "";
    }

    this.getUserInfoFn();
  },
  onShow() {
    if (!wx.getStorageSync("wx-session3rd")) {
      this.login();
    }
    this.getUserName();
  },
  methods: {
    async addAssessmentResultFn(item) {
      const params = {
        rightId: "2",
        personId:
          uni.getStorageSync("SxhPersonId") ||
          uni.getStorageSync("person-id").slice(2) ||
          undefined,
        typeName: item.value,
      };
      const res = await addAssessmentResult(params);
      this.showPersonalityBox = false;
      if (res.code == 200) {
        uni.navigateTo({
          url: `/pagesSub/careerAssessResultActNew/index?personId=${
            this.personId || uni.getStorageSync("person-id").slice(2)
          }&fromSxh=${this.fromSxh}`,
        });
      } else {
        uni.showToast({
          icon: "none",
          title: res.status_desc,
          duration: 2000,
        });
      }
    },
    openPersonalityBox() {
      this.showPersonalityBox = true;
    },
    testMore() {
      if (this.personId) {
        this.reqStart();
      } else {
        this.showLoginDialog();
      }
    },
    goToAccessResult() {
      if (this.personId) {
        this.reqCheckStatus();
      } else {
        this.showLoginDialog();
      }
    },
    getUserName() {
      // 这个uid一定要传，因为在interceptors中，没有传参的请求的请求头不会带上uid，而这个请求一定要uid
      getUserInfo({ uid: "" }).then((res) => {
        if (res.code == 200) {
          if (this.fromWhere == "junior") {
            this.imageSrc =
              "https://img3.job1001.com/ypMp/elan/images/career/vocationalAssessmentQuestion/long_cover_nopay.jpg?v=1";
          } else if (res.data.personName) {
            this.imageSrc =
              "https://img3.job1001.com/ypMp/elan/images/career/vocationalAssessmentQuestion/long_cover_nopay.jpg?v=1";
          }
        }
      });
    },
    handleStartAssessment() {
      // 如果来自双选会的首页，可以进行无限重测
      if (this.fromSxh == "sxh") {
        this.reqStart();
        return;
      }
      this.reqCheckStatus();
    },
    // 登录成功后处理
    handleJump(personId) {
      this.personId = personId;
      this.reqCheckStatus();
      return;
    },
    getCheckStatus() {
      if (!this.personId) {
        this.isShowTestMore = false;
        this.isShowStartTest = true;
        return;
      }
      const params = {
        personId: this.personId,
        assessmentType: this.assessmentType,
        assessmentVersion: uni.getStorageSync("assessmentVersion"), // v1 是老版本测评，v2 是新版本测评
      };
      checkStatus(params).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.isPay = res.data.isPay;
            this.resultId = res.data.resultId;
            this.isFinish = res.data.isFinish;
            this.hasRecord = res.data.hasRecord;
            if (this.isFinish) {
              this.isShowTestMore = true;
              this.isShowStartTest = false;
            } else {
              this.isShowTestMore = false;
              this.isShowStartTest = true;
            }
          }
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: "none",
          });
        }
      });
    },
    //获取当前用户答题状态
    reqCheckStatus() {
      console.log("111111111111111111111111");
      const params = {
        personId: this.personId,
        assessmentType: this.assessmentType,
        assessmentVersion: uni.getStorageSync("assessmentVersion"),
      };
      checkStatus(params).then((res) => {
        if (res.code == 200) {
          wx.reportEvent("start_measure_career_measure_click", {}); //职业测评-开始测评
          if (res.data) {
            this.isPay = res.data.isPay;
            this.resultId = res.data.resultId;
            this.isFinish = res.data.isFinish;
            this.hasRecord = res.data.hasRecord;
            wx.setStorageSync("assessmentId", this.resultId);
            //已支付
            if (this.isPay == 1) {
              console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
              //跳测评结果页（已解锁状态）
              if (this.fromWhere == "junior") {
                uni.redirectTo({
                  url: `/pagesSub/career/activity/JuniorCareerAssessResult?fromWhere=${this.fromWhere}&toBook=${this.toBook}`,
                });
              } else {
                uni.redirectTo({
                  url: `/pagesSub/careerAssessResultActNew/index?fromWhere=${this.fromWhere}&toBook=${this.toBook}&fromSxh=${this.fromSxh}`,
                });
                // if (!this.assessmentVersion || this.assessmentVersion == 1) {
                //   uni.redirectTo({
                //     url: `/pagesSub/career/activity/CareerAssessResultAct?fromWhere=${this.fromWhere}&toBook=${this.toBook}`
                //   });
                // } else if (this.assessmentVersion == 2) {
                //   uni.redirectTo({
                //     url: `/pagesSub/careerAssessResultActNew/index?fromWhere=${this.fromWhere}&toBook=${this.toBook}&fromSxh=${this.fromSxh}`
                //   });
                // }
              }
            } else {
              //已答完题
              if (this.isFinish == 1) {
                console.log("aaaaas");
                //跳测评结果页（未解锁状态）
                if (this.fromWhere == "junior") {
                  console.log("bbbbbbbbbbbbb");
                  uni.navigateTo({
                    url: `/pagesSub/career/activity/JuniorCareerAssessResult?fromWhere=${this.fromWhere}&toBook=${this.toBook}`,
                  });
                } else {
                  uni.redirectTo({
                    url: `/pagesSub/careerAssessResultActNew/index?fromWhere=${this.fromWhere}&toBook=${this.toBook}&fromSxh=${this.fromSxh}`,
                  });
                  // if (
                  //   !this.assessmentVersion ||
                  //   this.assessmentVersion == '1'
                  // ) {
                  //   uni.redirectTo({
                  //     url: `/pagesSub/career/activity/CareerAssessResultAct?fromWhere=${this.fromWhere}&toBook=${this.toBook}`
                  //   });
                  // } else if (this.assessmentVersion == '2') {
                  //   uni.redirectTo({
                  //     url: `/pagesSub/careerAssessResultActNew/index?fromWhere=${this.fromWhere}&toBook=${this.toBook}&fromSxh=${this.fromSxh}`
                  //   });
                  // }
                }
              } else {
                if (this.hasRecord == 1) {
                  //跳答题列表
                  uni.navigateTo({
                    url: `/pagesSub/career/activity/vocationalAssessmentAnswer?fromWhere=${this.fromWhere}&toBook=${this.toBook}&fromSxh=${this.fromSxh}`,
                  });
                } else {
                  this.reqStart();
                }
              }
            }
          }
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: "none",
          });
        }
      });
    },
    //没有答题记录时调用 开始测评答题
    reqStart() {
      uni.setStorageSync("assessmentVersion", 2); // 只要是开始答题了，就默认是v2版本测评
      const params = {
        personId: this.personId,
        assessmentType: this.assessmentType,
        assessmentVersion: 2, // 测评版本 1:v1版本 2：v2版本，只要是点击了答题，都是v2版本
      };
      start(params).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.resultId = res.data.id;
            uni.setStorageSync("assessmentId", this.resultId);
            //跳答题列表
            uni.navigateTo({
              url: `/pagesSub/career/activity/vocationalAssessmentAnswer?fromWhere=${this.fromWhere}&fromSxh=${this.fromSxh}`,
            });
          }
        }
      });
    },
    showLoginDialog() {
      this.$refs.loginDialog.setVisibility(true);
    },
    async loginSuccessBack() {
      this.personId = uni.getStorageSync("person-id").slice(2) || "";
      if (this.fromWhere == "junior") {
        this.getCheckStatus();
        await this.getUserInfoFn();
      }
    },
    async getUserInfoFn() {
      const params = { uid: "" };
      const res = await getUserInfo(params);
      if (res.code == 200) {
        // cardNoe和cardType是同时存在的
        await this.getPersonOrDefaultCardTypeFn();
        if (!res.data.cardNo) {
          // 说明此时没有绑卡 要自动绑卡(这里是针对中学生的项目)
          await this.cardRegistFn();
        } else {
          this.cardVersion = res.data.cardVersion;
        }
      }
    },
    async cardRegistFn() {
      const params = {
        cardKey: this.cardKey || "1", // cardType或者cardKe至少传一个
        cardType: this.cardType
          ? this.cardType
          : uni.getStorageSync("cardType") || this.cardType,
        sellId: +this.consultantId,
      };
      const res = await cardRegist(params);
      if (res.code != 200) {
        uni.showToast({ icon: "none", title: res.status_desc, duration: 1500 });
      }
    },
    async getPersonOrDefaultCardTypeFn() {
      const params = {
        personId: this.personId,
        cardSource: "HIGH_ASSESSMENT", // 如果是默认注册是关于高考的卡，就要穿这个参数获取到cardType
      };
      const res = await getPersonOrDefaultCardType(params);
      if (res.code == 200 && res.data.cardType) {
        this.cardType = res.data.cardType;
        uni.setStorageSync("cardType", res.data.cardType);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.allContainer {
  width: 100%;
  position: relative;

  .bottom-btn {
    display: flex;
    flex-direction: row;
    position: fixed;
    bottom: 98rpx;
    width: 90%;
    left: 5%;
    justify-content: space-evenly;
    align-items: center;
    .left-btn {
      width: 50%;
      height: 94rpx;
      color: #ffffff;
      text-align: center;
      background: #28cc75;
      border-radius: 8px;
      line-height: 94rpx;
      letter-spacing: 10rpx;
      font-size: 38rpx;
      font-weight: 500;
      margin-right: 22rpx;
    }
    .right-btn {
      flex: 1;
    }
  }
}

.image {
  width: 100vw;
  max-width: 100%;
}

.startAssessment {
  width: 100%;
  height: 94rpx;
  color: #ffffff;
  // position: fixed;
  // bottom: 55px;
  // left: 50%;
  // transform: translateX(-50%);
  text-align: center;
  background: #28cc75;
  border-radius: 8px;
  line-height: 94rpx;
  letter-spacing: 10rpx;
  font-size: 38rpx;
  font-weight: 500;
}

.junior-bottom {
  position: fixed;
  width: 100%;
  display: flex;
  flex-direction: row;
  bottom: 55px;

  .junior-test-more {
    width: 50%;
    height: 94rpx;
    margin-left: 27rpx;
    color: #ffffff;
    text-align: center;
    background: #ff711e;
    border-radius: 8px;
    line-height: 94rpx;
    letter-spacing: 10rpx;
    font-size: 38rpx;
    font-weight: 500;
    margin-right: 10rpx;
  }

  .junior-view-result {
    width: 50%;
    height: 94rpx;
    color: #ffffff;
    text-align: center;
    background: #28cc75;
    border-radius: 8px;
    line-height: 94rpx;
    letter-spacing: 10rpx;
    font-size: 38rpx;
    font-weight: 500;
    margin-left: 10rpx;
    margin-right: 27rpx;
  }
}

.lm-wechat {
  width: 91%;
  height: 94rpx;
  color: #ffffff;
  position: fixed;
  bottom: 55px;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  background: #28cc75;
  border-radius: 8px;
  line-height: 94rpx;
  letter-spacing: 10rpx;
  font-size: 38rpx;
  font-weight: 500;
}
.title {
  margin-top: 26rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.personality-box {
  margin-top: 40rpx;
  padding: 0 30rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 子项在主轴上的对齐方式 */
  align-items: stretch; /* 子项在交叉轴上的对齐方式 */
  .personality-item {
    width: calc(50% - 10px); /* 每个子项的宽度，减去间隔 */
    margin: 5px; /* 子项之间的间隔 */
    height: 80rpx;
    margin-bottom: 24rpx;
    line-height: 80rpx;
    text-align: center;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #222222;
    border-radius: 8rpx;
    border: 1px solid rgba(219, 219, 219, 0.5);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
